#!/usr/bin/env bash
echo "================终端管理系统================"
echo "注意:"
echo "    1:使用前,务必阅读工程目录下readme.txt."
echo "    2:使用前,务必保证电脑安装了redis并启动."
select ch in "【   启动系统   】" "【   关闭系统   】" "【   监听日志   】" "【   读取设备   】" "【安装Python依赖】" "【   安装Redis  】" "【   退出终端   】"; do
time=$(date "+%Y-%m-%d %H:%M:%S")
case ${ch} in
    "【   启动系统   】")
    ps -ef | grep app.py | grep -v grep | awk '{print $2}' | xargs kill -TERM
    adb_path=$(mdfind -name "platform-tools" | grep 'Android/sdk/platform-tools' | awk '{printf("%s/adb", $1)}')
    echo "adb 目录:${adb_path}"
    ${adb_path} devices | grep -Ev 'List of devices attached' | awk '{print $1}' > conf/devices_list.conf
    nohup python3 -u app.py >> run.log 2>&1 &
    echo "[${time}] 系统启动..."
    echo "You can now view ruyangmao in the browser."
    echo "  Local:            http://localhost:9990/"
    net_en0=$(ifconfig | grep -A 7 "en0:" | grep "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" | awk '{print $2}')
    if [[ "$net_en0" != "" ]];then
        echo "  On Your Network:  http://${net_en0}:9990/"
#        echo "http://${net_en0}:9990/" > conf/serve_ip_wifi.conf
    fi
    net_en1=$(ifconfig | grep -A 7 "en1:" | grep "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" | awk '{print $2}')
    if [[ "$net_en1" != "" ]];then
        echo "  On Your Network:  http://${net_en1}:9990/"
        # 写入WiFi ip
        echo "http://${net_en1}:9990" > conf/serve_ip_wifi.conf
    fi
    ;;
    "【   关闭系统   】")
    echo "[${time}] 系统关闭..."
    ps -ef | grep app.py | grep -v grep | awk '{print $2}' | xargs kill -TERM
    ps -ef | grep python | grep -v grep | awk '{print $1,$2,$3}' | xargs kill -TERM
    ;;
    "【   监听日志   】")
    open -a Terminal.app show_log.sh
    echo "[${time}] 监听日志..."
    ;;
    "【   读取设备   】")
    adb_path=$(mdfind -name "platform-tools" | grep 'Android/sdk/platform-tools' | awk '{printf("%s/adb", $1)}')
    echo "adb 目录:${adb_path}"
    ${adb_path} devices | grep -Ev 'List of devices attached' | awk '{print $1}' > conf/devices_list.conf
    echo "[${time}] 读取设备完成可以开始启动系统了..."
    ;;
    "【安装Python依赖】")
    echo "[${time}] 安装Python依赖..."
    pip3 install -r requirements.txt
    ;;
    "【   安装Redis  】")
    echo "[${time}] brew安装Redis..."
    brew reinstall redis
    brew services start redis
    brew services restart redis
    ;;
    "【   退出终端   】")
    echo "[${time}] 终端退出..."
    exit;
    ;;
    *)
    echo "未知命令"
    ;;
esac
done;